import { Sequelize } from 'sequelize-typescript';
import config from '../config/db';
import models from './models';

// 导入所有模型
const allModels = [];
for (const key in models) {
  if (Object.prototype.hasOwnProperty.call(models, key)) {
    const element = models[key];
    allModels.push(element);
  }
}

export const databaseProviders = [
  {
    provide: 'SequelizeToken',
    useFactory: async () => {
      const dbConfig = config.mysql;
      const sequelize = new Sequelize({
        dialect: 'mysql', //要链接数据库的语言
        host: dbConfig.host,
        port: dbConfig.port,
        username: dbConfig.username,
        password: dbConfig.password,
        database: dbConfig.database,
        logging: dbConfig.logging,
        dialectOptions: dbConfig.dialectOptions,
        pool: dbConfig.pool,
        define: dbConfig.define,
        query: dbConfig.query,
        timezone: dbConfig.timezone,
      });
      sequelize.addModels(allModels);
      await sequelize.sync();
      return sequelize;
    },
  },
];
